#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
FunASR WebSocket服务启动脚本
用于电话客服语音实时转录

使用方法:
    python start_funasr_server.py
    python start_funasr_server.py --port 8765 --host 0.0.0.0
"""

import sys
import os
import logging
import argparse

def setup_logging():
    """设置日志配置"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler('funasr_server.log', encoding='utf-8')
        ]
    )

def check_dependencies():
    """检查依赖是否安装"""
    required_packages = ['funasr', 'websockets', 'numpy', 'soundfile']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"  - {package}")
        print("\n请先安装依赖:")
        print("pip install -r funasr_requirements.txt")
        return False
    
    print("✅ 所有依赖包已安装")
    return True

def main():
    parser = argparse.ArgumentParser(
        description="启动 FunASR WebSocket 服务器",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  python start_funasr_server.py                    # 使用默认配置启动
  python start_funasr_server.py --port 8765        # 指定端口
  python start_funasr_server.py --host 0.0.0.0     # 允许外部访问
  python start_funasr_server.py --model paraformer-zh-streaming  # 指定流式模型

支持的模型:
  - paraformer-zh-streaming (默认, 中文流式)
  - paraformer-en-streaming (英文流式)
  
注意事项:
  - 首次运行会自动下载模型，请确保网络连接正常
  - 建议在GPU环境下运行以获得更好的性能
  - 确保防火墙允许指定端口的访问
  - 包含完整的VAD和标点符号功能
        """
    )
    
    parser.add_argument(
        "--host", 
        default="0.0.0.0", 
        help="服务器主机地址"
    )
    parser.add_argument(
        "--port", 
        type=int, 
        default=8765, 
        help="服务器端口"
    )
    parser.add_argument(
        "--model", 
        default="paraformer-zh-streaming", 
        help="流式ASR模型名称"
    )
    
    args = parser.parse_args()
    
    print("🎤 FunASR WebSocket 服务器启动器")
    print("=" * 50)
    print(f"📍 服务器地址: {args.host}:{args.port}")
    print(f"🤖 流式模型: {args.model}")
    print("✅ 包含功能: VAD + ASR + 标点符号")
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 启动服务器
    start_server(args.host, args.port, args.model)

def start_server(host="0.0.0.0", port=8765, model="paraformer-zh-streaming"):
    """启动 FunASR WebSocket 服务器"""
    try:
        print("🚀 正在启动服务器...")
        print("按 Ctrl+C 停止服务")
        print("=" * 50)
        
        # 导入并启动服务器
        from funasr_websocket_server import FunASRWebSocketServer
        import asyncio
        
        server = FunASRWebSocketServer(host=host, port=port, streaming_model=model)
        
        asyncio.run(server.start_server())
        
    except KeyboardInterrupt:
        print("\n✅ 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        print("\n💡 解决建议:")
        print("1. 检查端口是否被占用")
        print("2. 确认 FunASR 安装正确")
        print("3. 检查网络连接（首次需下载模型）")
        print("4. 确保使用支持的流式模型名称")

if __name__ == "__main__":
    main() 